<?php

namespace app\controllers;

use Yii;
use app\models\Mobie;
use app\models\MobieSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

use Qiniu\Auth;

/**
 * MobieController implements the CRUD actions for Mobie model.
 */
class MobieController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {

         if( Yii::$app->user->isGuest){
            $this->redirect('?r=site/login');
        }    


        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
           
        ];
    }

    public function beforeAction($action) {
    $this->enableCsrfValidation = false;
    return parent::beforeAction($action);
}


    /**
     * Lists all Mobie models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new MobieSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    
    public function actionAjax($tab=1)
    {
       $sql = "select * from orders where status = 0 and order_type = ".$tab." order by order_sort desc;";
       
       $data = Yii::$app->db->createCommand($sql)->queryAll();

       echo json_encode($data);
    }

    public function actionAjaxIdByName($name){
        $sql = "select * from user_info where name = '".$name."' ;";
       $data = Yii::$app->db->createCommand($sql)->queryAll();

       echo json_encode($data);
    }

    public function actionAjaxIdByClubName($name){
        $sql = "select * from club_info where name = '".$name."' ;";
       
       $data = Yii::$app->db->createCommand($sql)->queryAll();

       echo json_encode($data);
    }

    public function  actionAjaxSaveData(){

        $str = $_POST["data"];
        // $name = trim($name);
        // echo $str;

        $data = json_decode($str,true);

        $task_id = time().rand(0,1000); 

        for ($i=0; $i < count($data) ; $i++) { 
            try {
    
            
            $info = $data[$i];
            $table_id = '0';
            if(isset($info["桌号"])){
                $table_id = $info["桌号"];    
            }
            $poker_name = "";
            if(isset($info["ID"])){
                $poker_name =  $info["ID"];
            }else{
                continue;
            }

            $score = 0;
            if(isset($info["战绩"])){
                $score =  $info["战绩"];    
            }else{
                continue;
            }

            $in_score = 0;
            if(isset($info["客人结算"])){
                $in_score =  $info["客人结算"];    
            }
            
            $out_score = 0;
            if(isset($info["反水"])){
                $out_score =  $info["反水"];    
            }
            
            $end_score = 0;
            if(isset($info["最终结算"])){
                $end_score = $info["最终结算"];
            }

            $club_id = 0;
            if(isset($info["俱乐部id"])){
                $club_id =  $info["俱乐部id"];    
            }

            $user_id = 0;
            if(isset($info["用户id"])){
                $user_id =  $info["用户id"];
            }

            $agent_id =  0;
            if(isset($info["代理id"])){
                $agent_id =  $info["代理id"];
                if($agent_id == '无'){
                    $agent_id = 0;
                }
            }

            $club_name =  $info["俱乐部"];
            $ts = $info["时间"];
            
            $agent_name =  $info["代理名字"];

            $sql = "insert into user_poker set user_id = $user_id,user_agent_id='$agent_id',table_id='$table_id' , poker_name = '$poker_name' ,score = '$score' ,in_score = '$in_score',out_score = '$out_score',ts = '$ts',end_score = '$end_score',club_id = '$club_id' , task_id = '$task_id'; ";
            // echo $sql;
            Yii::$app->db->createCommand($sql)->execute();

            } catch (Exception $e) {
                echo 'Caught exception: ',  $e->getMessage(), "\n";
            }

        }

        echo '{"code":0,"msg":"ok"}';

    }


     public function actionAjaxAgents(){
        $name = $_POST["ids"];
        $name = trim($name);
        $values = explode("||",$name);
        
        
        $ids = join(",",$values);

        $sql = "select ua.user_id ,ua.user_agent_id , ui.name from user_agent ua,user_info ui where ua.user_agent_id = ui.user_id and ua.user_id in ($ids)";

        $data = Yii::$app->db->createCommand($sql)->queryAll();

        $info =array('cnt'=>0);

        foreach ($data as $key => $value) {
            $info['ui_'.$value["user_id"]] = $value["user_agent_id"];
            $info["ua_".$value["user_agent_id"]] = $value["name"];
        }
        echo json_encode($info);
    }


    public function actionAjaxNames(){
        $name = $_POST["name"];
        $name = trim($name);
        $values = explode("||",$name);
        $info =array('cnt'=>0);
        foreach ($values as $key => $value) {
            $na  = trim($value);
            $user_id = 0;
            if($na!=""){

                $sql = "select * from user_info where name = '".$na."' ;";
                $data = Yii::$app->db->createCommand($sql)->queryAll();
                if(count($data)==0){
                     $sql = "insert into user_info set name = '$na' ;";
                     Yii::$app->db->createCommand($sql)->execute();

                    $sql = "select * from user_info where name = '".$na."' ;";
                    $data = Yii::$app->db->createCommand($sql)->queryAll();

                     $user_id = $data[0]["user_id"];
                     $info[$na] = $user_id;
                }else{
                    $user_id = $data[0]["user_id"];
                    $info[$na] = $user_id;
                }
            }
        }
        echo json_encode($info);
    }



public function actionAjaxClubs(){
        $name = $_POST["name"];
        $name = trim($name);
        $values = explode("||",$name);
        $info =array('cnt'=>0);
        foreach ($values as $key => $value) {
            $na  = trim($value);
            $user_id = 0;
            if($na!=""){

                $sql = "select * from club_info where name = '".$na."' ;";
                $data = Yii::$app->db->createCommand($sql)->queryAll();
                if(count($data)==0){
                     $sql = "insert into club_info set name = '$na' ;";
                     Yii::$app->db->createCommand($sql)->execute();

                    $sql = "select * from club_info where name = '".$na."' ;";
                    $data = Yii::$app->db->createCommand($sql)->queryAll();

                     $user_id = $data[0]["club_id"];
                     $info[$na] = $user_id;
                }else{
                    $user_id = $data[0]["club_id"];
                    $info[$na] = $user_id;
                }
            }
        }
        echo json_encode($info);
    }











    public function actionAddClub($name){
        $sql = "insert into club_info set name = '$name' ;";
        $data = Yii::$app->db->createCommand($sql)->execute();

         $sql = "select * from club_info where name = '".$name."' ;";
       
       $data = Yii::$app->db->createCommand($sql)->queryAll();

        echo json_encode($data);
    }  

    public function actionAddUser($name){
        $sql = "insert into user_info set name = '$name' ;";
        $data = Yii::$app->db->createCommand($sql)->execute();

          $sql = "select * from user_info where name = '".$name."' ;";
       $data = Yii::$app->db->createCommand($sql)->queryAll();

        echo json_encode($data);
    }


    public function actionBannermajax()
    {
        $sql = "select * from banner limit 1";
        $data = Yii::$app->db->createCommand($sql)->queryAll();
       echo json_encode($data);
    }


    public function  actionToken(){
        // require_once __DIR__ . './../autoload.php';

        

        // $accessKey = 'bIEEmQ3ZrjrQ0c44TRn4t-kl--2xN4fhz7LclsWZ';
        // $secretKey = 'Eosr0D-TnXS6pBheDVlfWjh-RoXu5P-jiUnwSgYv';
        // $auth = new Auth($accessKey, $secretKey);

        // $bucket = 'Bucket_Name';
        // $upToken = $auth->uploadToken($bucket);
        // echo $upToken;

        $xml = file_get_contents("https://sslsharecircle.51yund.com/getQiniuToken?source=city_activity");
        echo $xml;

    }

    public function actionImageurl($filename,$source){
        
        $xml = file_get_contents("https://sslsharecircle.51yund.com/getQiniuImgUrl?filename=".$filename."&source=".$source);
        echo $xml;

    }





    /**
     * Displays a single Mobie model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Mobie model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Mobie();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->order_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Mobie model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->order_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Mobie model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Mobie model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Mobie the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Mobie::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
